package com.gzbugu.polytechsasia.servlet;

import com.gzbugu.polytechsasia.factory.ServiceFactory;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA. User: Bokchoy Date: 11/1/12 Time: 9:53 AM
 */
/*
 * Servlet implementation class of addArticle
 */

public class AddArticle extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public AddArticle() {
		super();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		RequestDispatcher rd = req.getRequestDispatcher("asdaskd"); // 为跳转指向一个不存在的页，触发404状态
		rd.forward(req, resp); // 服务器跳转
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String content = req.getParameter("content");
		String title = req.getParameter("title");
		int type;
		try {
			type = Integer.parseInt(req.getParameter("type"));
		} catch (NumberFormatException e) {
			type = -1; // 未分类文章被冠以-1做标记
		}
		PrintWriter out = resp.getWriter();
		if ("".equals(content) || content == null || "".equals(title)
				|| title == null) {
			out.println("0");
		} else if (ServiceFactory.getAddArticleService().addArticle(title,
				content, type)) {
			resp.sendRedirect("en/admin/manage.jsp");
		} else {
			resp.sendRedirect("en/admin/add.jsp");
		}
		out.flush();
		out.close();
	}
}
